define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'accounts_receivable/index' + location.search,
                    add_url: 'accounts_receivable/add',
                    edit_url: 'accounts_receivable/edit',
                    del_url: 'accounts_receivable/del',
                    multi_url: 'accounts_receivable/multi',
                    import_url: 'accounts_receivable/import',
                    table: 'accounts_receivable',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {field: 'sales_shipment_id', title: __('Sales_shipment_id'), operate: 'LIKE'},
                        {field: 'customer_name', title: __('Customer_name'), operate: 'LIKE'},
                        {field: 'product_name', title: __('Product_name'), operate: 'LIKE'},
                        // {field: 'unit_price', title: __('Unit_price'), operate:'BETWEEN'},
                        // {field: 'quantity', title: __('Quantity')},
                        {field: 'reconciliation_date', title: __('Reconciliation_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'receivable_amount', title: __('Receivable_amount'), operate:'BETWEEN'},
                        {field: 'actual_received_amount', title: __('Actual_received_amount'), operate:'BETWEEN'},
                        {field: 'received_amount', title: __('Received_amount'), operate:'BETWEEN'},
                        {field: 'payment_date', title: __('Payment_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'unpaid_amount', title: __('Unpaid_amount'), operate:'BETWEEN'},
                        {field: 'invoice_time', title: __('Invoice_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'invoice_amount', title: __('Invoice_amount'), operate:'BETWEEN'},
                        {field: 'invoice_number', title: __('Invoice_number'), operate: 'LIKE'},
                        {field: 'settlement_status_text', title: __('Settlement_status'), operate: 'LIKE', searchList: Controller.api.settlementStatusList},
                        {field: 'paid_amount', title: __('Paid_amount'), operate: 'BETWEEN'},
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
    $(document).on("change", "#c-sales_shipment_id", function(){
        var sales_shipment_id = $(this).val();
        var order_id = "";
        var money = 0;
        if (sales_shipment_id) {
            $.ajax({
                url: 'sales_shipment/getById',
                type: 'post',
                data: {id: sales_shipment_id},
                success: function(response) {
                    if (response.code === 200) {
                        order_id = response.data.order_id;
                        getCustomerDemandData(order_id);
                    } else {
                        console.error(response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('请求失败:', error);
                }
            });
        }
        
        function getCustomerDemandData(order_id) {
            $.ajax({
                url: 'accounts_receivable/getTableList',
                type: 'post',
                data: {order_ids: order_id},
                dataType: 'json',
                success: function(response) {
                    if (response.code === 1) {
                        var customerDemandTableBody = $("#customer-demand-table tbody");
                        customerDemandTableBody.empty();
                        if (response.data.length > 0) {
                            $("#customer-demand-table").show();
                            $.each(response.data, function(i, item) {
                                var amount = item.unit_price * item.quantity;
                                var row = '<tr data-product-id="' + item.product_id + '" data-customer-id="' + item.customer_id + '">' +
                                    '<td>' + item.product_name + '</td>' +
                                    '<td>' + item.customer_name + '</td>' +
                                    '<td>' + item.product_id + '</td>' +
                                    '<td>' + item.customer_id + '</td>' +
                                    '<td>' + item.unit_price + '</td>' +
                                    '<td><input type="number" class="form-control quantity-input" ' + 
                                    'value="' + item.quantity + '" ' +
                                    'min="0" data-unit-price="' + item.unit_price + '"></td>' +
                                    '<td class="amount">' + amount + '</td>' +
                                    '</tr>';
                                customerDemandTableBody.append(row);
                                money += amount;
                            });
                            // 设置金额字段并触发change事件
                            $("#c-receivable_amount").val(money).trigger('change');
                            $("#c-unpaid_amount").val(money).trigger('change');
                        } else {
                            $("#customer-demand-table").hide();
                        }
                    } else {
                        console.error(response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('请求失败:', error);
                }
            });
        }
    });

    // 监听数量变化，更新金额
    $(document).on("change", ".quantity-input", function() {
        updateAmounts();
    });

    Controller.api.bindevent();
},
                edit: function () {
            // 初始化编辑页面的客户需求表格
            var customerDemandJson = $("#c-customer_demand_json").val();
            if (customerDemandJson) {
                var parsedData = JSON.parse(customerDemandJson);
                renderCustomerDemandTable(parsedData);
            }

            // 监听销售出货单变化
            $(document).on("change", "#c-sales_shipment_id", function(){
                var sales_shipment_id = $(this).val();
                var order_id = "";
                if (sales_shipment_id) {
                    $.ajax({
                        url: 'sales_shipment/getById',
                        type: 'post',
                        data: {id: sales_shipment_id},
                        success: function(response) {
                            if (response.code === 200) {
                                order_id = response.data.order_id;
                                getCustomerDemandData(order_id);
                            } else {
                                console.error(response.msg);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败:', error);
                        }
                    });
                }
                
                function getCustomerDemandData(order_id) {
                    $.ajax({
                        url: 'accounts_receivable/getTableList',
                        type: 'post',
                        data: {order_ids: order_id},
                        dataType: 'json',
                        success: function(response) {
                            if (response.code === 1) {
                                renderCustomerDemandTable(response.data);
                            } else {
                                console.error(response.msg);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败:', error);
                        }
                    });
                }
            });

            // 监听数量变化
            $(document).on("change", ".quantity-input", function() {
                updateAmountsAndJson();
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),
                    function(data, ret) { // success callback
                        Fast.api.close(data);
                    },
                    function(data, ret) { // error callback
                        // 错误处理
                    },
                    function(data, ret) { // submit callback
                        updateAmountsAndJson();
                        return true;
                    },
                    function(data, ret) { // aftersubmit callback
                        // 提交后处理
                    }
                );
            },
            settlementStatusList: {
                '已结清': __('已结清'),
                '未结清': __('未结清'),
                '剩余未结清': __('剩余未结清')
            },
            
        }
        
    };
    // 更新金额和JSON数据的通用函数
    function updateAmountsAndJson() {
        var customerDemandData = [];
        var totalAmount = 0;
        
        $("#customer-demand-table tbody tr").each(function() {
            var $row = $(this);
            var $quantityInput = $row.find(".quantity-input");
            var quantity = parseFloat($quantityInput.val()) || 0;
            var unitPrice = parseFloat($quantityInput.data("unit-price")) || 0;
            var amount = quantity * unitPrice;
            
            $row.find(".amount").text(amount.toFixed(2));
            totalAmount += amount;
            
            customerDemandData.push({
                product_name: $row.find("td:eq(0)").text(),
                customer_name: $row.find("td:eq(1)").text(),
                product_id: $row.find("td:eq(2)").text(),
                customer_id: $row.find("td:eq(3)").text(),
                unit_price: unitPrice,
                quantity: quantity,
                amount: amount
            });
        });
        
        // 更新总金额字段
        $("#c-receivable_amount").val(totalAmount.toFixed(2));
        $("#c-unpaid_amount").val(totalAmount.toFixed(2));
        
        // 更新JSON数据
        $("#c-customer_demand_json").val(JSON.stringify(customerDemandData));
    }
    // 更新金额的通用函数
function updateAmounts() {
    var totalAmount = 0;
    
    $("#customer-demand-table tbody tr").each(function() {
        var $row = $(this);
        var $quantityInput = $row.find(".quantity-input");
        var quantity = parseFloat($quantityInput.val()) || 0;
        var unitPrice = parseFloat($quantityInput.data("unit-price")) || 0;
        var amount = quantity * unitPrice;
        
        $row.find(".amount").text(amount.toFixed(2));
        totalAmount += amount;
    });
    
    // 更新金额字段并触发change事件
    $("#c-receivable_amount").val(totalAmount.toFixed(2)).trigger('change');
    $("#c-unpaid_amount").val(totalAmount.toFixed(2)).trigger('change');
}

// 渲染客户需求表格的通用函数
function renderCustomerDemandTable(data) {
    var customerDemandTableBody = $("#customer-demand-table tbody");
    customerDemandTableBody.empty(); // 清空现有数据
    var totalAmount = 0;

    if (data.length > 0) {
        $("#customer-demand-table").show();
        $.each(data, function(i, item) {
            var amount = (item.quantity * item.unit_price).toFixed(2);
            var row = '<tr data-product-id="' + item.product_id + '" data-customer-id="' + item.customer_id + '">' +
                '<td>' + item.product_name + '</td>' +
                '<td>' + item.customer_name + '</td>' +
                '<td>' + item.product_id + '</td>' +
                '<td>' + item.customer_id + '</td>' +
                '<td>' + item.unit_price + '</td>' +
                '<td><input type="number" class="form-control quantity-input" ' +
                'value="' + item.quantity + '" ' +
                'min="0" data-unit-price="' + item.unit_price + '"></td>' +
                '<td class="amount">' + amount + '</td>' +
                '</tr>';
            customerDemandTableBody.append(row);
            totalAmount += parseFloat(amount);
        });
        $("#c-receivable_amount").val(totalAmount.toFixed(2));
        $("#c-unpaid_amount").val(totalAmount.toFixed(2));
    } else {
        $("#customer-demand-table").hide();
    }
}
    return Controller;
});
